package com.company.ljh.medium;
/**
 * 19.删除链表倒数第n个节点
 */

import com.company.ljh.utils.ListNode;

/**
 * @description:
 * @projectName:leet_code
 * @see:com.company.ljh.medium
 * @author:ljh
 * @createTime:2022/6/1 16:02
 * @version:1.0
 */
public class 删除链表的倒数第N个结点 {
    /**
     * 快慢指针，主要是小心删除自己的情况
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head;
        ListNode slow = head;
        for(int i =0;i<n;i++){
            //快指针先走n步
            fast = fast.next;
        }

        while(fast!=null&&fast.next !=null){
            slow = slow.next;
            fast = fast.next;
        }
        if(fast == null){
            //删除自己
            head = head.next;
        }else
            //删除slow的后一个节点
            slow.next = slow.next.next;
        return head;
    }
}
